package com.utils.exception;

import com.utils.Response;
import com.utils.ResultCodeEnum;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;

/**
 * 全局异常处理类
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**-------- 通用异常处理方法 --------**/
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Response error(Exception e) {
        System.out.println(1);
        e.printStackTrace();
        return Response.error();
    }

    /**-------- 指定异常处理方法：空指针异常 --------**/
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public Response error(NullPointerException e) {
        System.out.println(2);
        e.printStackTrace();
        return Response.setResult(ResultCodeEnum.NULL_POINT);
    }

    /**-------- 客户端异常处理方法 --------*/
    @ExceptionHandler(HttpClientErrorException.class)
    @ResponseBody
    public Response error(IndexOutOfBoundsException e) {
        System.out.println(3);
        e.printStackTrace();
        return Response.setResult(ResultCodeEnum.HTTP_CLIENT_ERROR);
    }

    /**-------- 自定义定异常处理方法 --------**/
    @ExceptionHandler(CMSException.class)
    @ResponseBody
    public Response error(CMSException e) {
        System.out.println(4);
        e.printStackTrace();
        return Response.error().message(e.getMessage()).code(e.getCode());
    }
}